package top.hkyzf.study.leetcode.tree;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-2-22 15:17
 */
public class 二叉搜索树中的搜索_700 {
    public TreeNode searchBST(TreeNode root, int val) {
        return dfs(root, val);
    }

    TreeNode dfs(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        TreeNode node = dfs(root.left, val);
        if (node == null) {
            return dfs(root.right, val);
        } else {
            return node;
        }
    }

    @Test
    public void testSearchBST () {
        TreeNode node4 = new TreeNode(3);
        TreeNode node3 = new TreeNode(1);
        TreeNode node2 = new TreeNode(7);
        TreeNode node1 = new TreeNode(2, node3, node4);
        TreeNode root = new TreeNode(4, node1, node2);
        TreeNode node = searchBST(root, 5);
        if (node != null) {
            node.print();
        } else {
            System.out.println("空");
        }
    }
}
